<template>
  <el-dialog v-model="dialogVisible" draggable :title="dialogProps.title" width="60%">
    <div style="margin-top: -10px; margin-bottom: 10px">
      <el-input v-model="searchKw" placeholder="请输入" :prefix-icon="Search" @input="searchInp" />
    </div>
    <div class="selector-container">
      <tree-filter :data="treeFilterData" :default-value="initParam" label="name" :show-search="false" @change="changeTreeFilter" />
      <div class="table-box">
        <pro-table
          ref="proTable"
          :columns="dialogProps.columns"
          :data="tableData"
          :indent="20"
          :margin-border="false"
          :max-height="280"
          :pagination="false"
          :row-key="dialogProps.mate"
          :tool-button="false"
          @selection-change="changeSelection"
        />
      </div>
    </div>
    <div v-if="dialogProps.selType === 'selection'" class="selector-footer">
      <div class="flx-justify-between pt10 pb10">
        <span>已选择({{ tags.length }})</span>
        <el-button type="danger" @click="clearSelection">清空</el-button>
      </div>
      <div class="inner">
        <el-tag v-for="tag in tags" :key="tag.id" class="mr6 mb6" closable @close="handleDelTag(tag.id)">
          {{ tag.name }}
        </el-tag>
      </div>
    </div>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onEmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="selectGoods">
import { Search } from '@element-plus/icons-vue'
import { useDebounceFn } from '@vueuse/core'
import { nextTick, ref, watch } from 'vue'
import { Inventory } from '~/src/api/interface/goods'
import { ColumnProps, ProTableInstance } from '../ProTable/interface'
import TreeFilter from '/@vab//components/TreeFilter/index.vue'
import ProTable from '/@vab/components/ProTable/index.vue'
interface DialogProps {
  title: string
  isView: boolean
  selType?: string
  selTags?: Inventory.ResGoodsList[]
  columns?: ColumnProps[]
  idName?: string
  index?: number | string
  searchVal?: string | number
  mate?: string
  apiParams?: {}
  api?: (params: any) => Promise<any>
  treeApi?: (params: any) => Promise<any>
  type?: string
}
const dialogProps = ref<DialogProps>({
  isView: false,
  selType: 'selection',
  title: '',
  index: -1,
  searchVal: '',
  mate: 'id',
})
const proTable = ref<ProTableInstance>()

const initParam = ref(0)
const dialogVisible = ref(false)
const treeFilterData = ref<any>([])
const tableData = ref<Inventory.ResGoodsList[]>([])
const tags = ref<Inventory.ResGoodsList[]>([])
const searchKw = ref('')
const emit = defineEmits(['selectedList', 'radio']) // 指定组件可以触发的事件

// 树形筛选切换
const changeTreeFilter = (id: number) => {
  initParam.value = id
  tableData.value = []
  getTableData()
}

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  dialogProps.value = params
  dialogProps.value.selType = params.selType || 'selection'
  tags.value = dialogProps.value.selTags
  searchKw.value = dialogProps.value.searchVal
  dialogVisible.value = true
  getTreeFilter()
}

const getTreeFilter = async () => {
  const { data } = await dialogProps.value.treeApi({ pageNum: 1, pageSize: 9999 })
  treeFilterData.value = data.list || data
  initParam.value = 0
  await getTableData()
}

// 搜索数据
const searchInp = useDebounceFn(() => {
  getTableData()
}, 800)

const getTableData = () => {
  tableData.value = []
  dialogProps
    .value!.api({
      name: searchKw.value,
      pageNum: 1,
      pageSize: 9999,
      isDefault: 0,
      isRetail: 1,
      ...dialogProps.value.apiParams,
      [dialogProps.value.idName]: initParam.value,
    })
    .then((res) => {
      // 处理数据
      tableData.value = JSON.parse(JSON.stringify(res.data.list)) ?? []
      if (dialogProps.value.selType === 'selection') {
        nextTick(() => {
          // const tags_Ids = tags.value.map(i => i.id);
          if (dialogProps.value.mate) {
            // 先判断mate不是undefined
            const tags_Ids = tags.value.map((i) => i.id)
            tableData.value.forEach((item) => {
              if (tags_Ids.includes(item[dialogProps.value.mate as keyof typeof item])) {
                proTable.value!.element!.toggleRowSelection(item, true)
              }
            })
          }
        })
      }
    })
    .catch(() => {
      tableData.value = []
    })
}

const handleDelTag = (tag?: string | number) => {
  let index1 = tags.value.findIndex((item) => item.id === tag)
  let index2 = tableData.value.findIndex((item) => item.id === tag)
  if (index1 > -1) {
    tags.value.splice(index1, 1)
  }
  if (index2 > -1) {
    proTable.value!.element.toggleRowSelection(tableData.value[index2], false)
  }
}

// 清空选择
const clearSelection = () => {
  if (tags.value.length !== 0) {
    tags.value.splice(0, tags.value.length)
    proTable.value!.element.clearSelection()
  }
}

// 提交数据（选择菜品）
const onEmit = () => {
  if (dialogProps.value.selType === 'radio') {
    emit('radio', { data: proTable.value!.radio, index: dialogProps.value.index })
  } else if (dialogProps.value.selType === 'selection') {
    emit('selectedList', {
      list: tags.value,
      title: dialogProps.value.title,
      index: dialogProps.value.index,
      type: dialogProps.value.type,
    })
  }
  // 搜索的 内容
  searchKw.value = ''
  dialogVisible.value = false
}

watch(dialogVisible, (newValue) => {
  if (!newValue) {
    tags.value = []
    proTable.value!.element!.clearSelection()
  }
})

const changeSelection = (selection: any[]) => {
  tags.value = selection
}

defineExpose({
  acceptParams,
})
</script>
<style scoped lang="scss">
@use './index.scss';
</style>
